---
import Layout from '../pages/layouts/Layout.astro';
import Header from '../components/Header.astro';
import Survey from '../components/Survey.jsx';
import SurveyForm from '../components/SurveyForm.jsx'; 
import TopicAgenda from '../components/topicAgenda/TopicAgenda.jsx';
import TreeviteLoginCodeModal from '../components/TreeviteLoginCodeModal.jsx';
import TreeviteInvites from '../components/TreeviteInvites.jsx';
import XidOidcConflictWarning from '../components/XidOidcConflictWarning.jsx';
import { getTranslations } from '../strings/strings.js';
import PolisNet from '../lib/net';
import { marked } from 'marked';
import DonateMessage from '../components/DonateMessage';
import VisualizationContainer from '../components/VisualizationContainer';

const { conversation_id } = Astro.params;

// Validate conversation_id - reject common invalid requests
if (!conversation_id || 
    conversation_id === 'favicon.ico' || 
    conversation_id === 'robots.txt' ||
    conversation_id === 'sitemap.xml' ||
    conversation_id.includes('.') || // Reject any ID with file extensions
    conversation_id.length < 3) { // Reject very short IDs
  return Astro.redirect('/404');
}

// Load translations first so we can use them in error messages
const s = await getTranslations();

let initialData;
let fetchError = null;

try {
  const xid = Astro.url.searchParams.get('xid');
  const x_name = Astro.url.searchParams.get('x_name');
  const x_profile_image_url = Astro.url.searchParams.get('x_profile_image_url');

  const apiParams: Record<string, any> = {
    conversation_id,
    includePCA: false
  };

  if (xid) {
    apiParams.xid = xid;
  }
  if (x_name) {
    apiParams.x_name = x_name;
  }
  if (x_profile_image_url) {
    apiParams.x_profile_image_url = x_profile_image_url;
  }

  initialData = await PolisNet.polisGet('/participationInit', apiParams);
  // Note: JWT token handling will be done client-side since this is SSR
  // The handleJwtFromResponse function will be called when the page hydrates
} catch (error: unknown) {
  console.error("Failed to fetch conversation data:", error);
  
  // Type-safe error handling
  const errorMessage = error instanceof Error ? error.message : String(error);
  const errorResponseText = error && typeof error === 'object' && 'responseText' in error 
    ? String(error.responseText) 
    : '';
  const errorCause = error instanceof Error ? error.cause : undefined;
  const errorCode = errorCause && typeof errorCause === 'object' && 'code' in errorCause 
    ? String(errorCause.code) 
    : undefined;
  
  console.error("[DEBUG] Error details:", {
    message: errorMessage,
    responseText: errorResponseText,
    cause: errorCause,
    code: errorCode,
    stack: error instanceof Error ? error.stack : undefined
  });

  // Handle specific error cases
  if (errorResponseText.includes('polis_err_xid_required')) {
    fetchError = s.xidRequired || "This conversation requires an XID (external identifier) to participate. Please use the proper link provided to you.";
  } else {
    fetchError = `Could not load this conversation. Error: ${errorMessage}. Please check the ID and try again.`;
  }
}

let surveyDetails, firstStatement, isConversationActive;
if (initialData) {
  surveyDetails = {
    title: initialData.conversation.topic,
    description: initialData.conversation.description,
    requiresInviteCode: initialData.conversation.treevite_enabled,
  };
  
  firstStatement = {
    tid: initialData.nextComment?.tid,
    txt: initialData.nextComment?.txt,
    remaining: initialData.nextComment?.remaining,
  };

  isConversationActive = initialData.conversation.is_active;
}

const hideHeader = Astro.url.searchParams.get('hide_header');
---
<Layout title={surveyDetails?.title ?? 'Loading Conversation...'}>
  {/* Handle JWT token from initial data on client side - MUST be synchronous to avoid race conditions */}
  <script define:vars={{ initialData }} is:inline>
    if (initialData && initialData.auth && initialData.auth.token) {
      // Store the token synchronously before any React components try to read it
      const token = initialData.auth.token;
      
      try {
        // Decode JWT to get conversation_id
        const parts = token.split(".");
        if (parts.length === 3) {
          const payload = JSON.parse(atob(parts[1]));
          const conversationId = payload.conversation_id;
          
          if (conversationId && window.localStorage) {
            const tokenKey = "participant_token_" + conversationId;
            window.localStorage.setItem(tokenKey, token);
            
            // Dispatch event to notify components
            window.dispatchEvent(new CustomEvent('polis-token-update', { 
              detail: { conversation_id: conversationId } 
            }));
          }
        }
      } catch (e) {
        console.error('[Token] Error storing JWT:', e);
      }
    }
  </script>
  
  <div class="container">
    {hideHeader ? null : <Header />}
    
    <XidOidcConflictWarning client:load s={s} />

    {fetchError ? (
      <div class="error-message">
        <h2>Oops!</h2>
        <p>{fetchError}</p>
      </div>
    ) : initialData ? (
      <>
        <h1>
          {surveyDetails?.title}
          {!isConversationActive && <span class="closed-badge">closed</span>}
        </h1>
        <p class="description" set:html={marked.parse(surveyDetails?.description)}></p>

        {isConversationActive ? (
          <>
            {surveyDetails?.requiresInviteCode && (<TreeviteLoginCodeModal client:only="react" s={s} />)}
            <TopicAgenda 
              client:only="react"
              conversation_id={conversation_id}
              requiresInviteCode={surveyDetails?.requiresInviteCode}
              s={s}
            />
            <p class="conversation-intro" set:html={s.participantHelpWelcomeText}></p>
            <Survey 
              client:load 
              initialStatement={firstStatement}
              conversation_id={initialData.conversation.conversation_id}
              s={s}
              requiresInviteCode={surveyDetails?.requiresInviteCode}
            />
            <SurveyForm client:load s={s} conversation_id={conversation_id} requiresInviteCode={surveyDetails?.requiresInviteCode} />
            {surveyDetails?.requiresInviteCode && (<TreeviteInvites client:only="react" conversation_id={conversation_id} s={s} />)}
          </>
        ) : (
          <div class="footer-spacer"></div>
        )}

        {initialData.conversation.vis_type === 1 && (
          <VisualizationContainer client:only="react" conversation_id={conversation_id} />
        )}
      </>
    ) : (
      <p>Loading...</p>
    )}

    <div style="margin-top: 3rem;">
      <div class="logo">p</div>
      <div class="footer-links">
        <a href="/privacy" target="_blank" rel="noopener noreferrer">{s.privacy}</a>
        <a href="/tos" target="_blank" rel="noopener noreferrer">{s.TOS}</a>
      </div>
      <DonateMessage client:load />
    </div>
  </div>
</Layout>
